package com.yutian.example.demo.common.vo;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.yutian.example.demo.common.utils.StringUtil;
import lombok.Data;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.Assert;

import java.util.List;

/**
 * PageData作为HttpResponse的data
 * @param <T>
 */
@Data
public class PageData<T> {
    private transient PageImpl<T> page;
    /**
     * 总数
     */
    private long totalElements;

    /**
     * 总页数
     */
    private int totalPages;

    /**
     * 当前第几页
     * 注：从1开始
     */
    private int pageNumber;

    /**
     * 每页大小
     */
    private int pageSize;

    /**
     * 排序内容
     * 格式：+id,-name
     */
    private String sorts;

    /**
     * 当前页的内容
     */
    private List<T> rows;

    public PageData(List<T> content, Pageable pageable, long total) {
        Assert.notNull(pageable.getPageSize(), "Content must not be null!");
        Assert.notNull(pageable.getPageNumber(), "Pageable must not be null!");
        this.page = new PageImpl<T>(content, pageable, total);
        this.rows = content;
        this.totalElements = page.getTotalElements();
        this.totalPages = page.getTotalPages();
        this.pageNumber = page.getNumber() + 1;
        this.pageSize = page.getSize();
        this.sorts = toSorts(page.getSort());
    }

    public PageData(List<T> content) {
        this.page = new PageImpl<>(content);
        this.rows = content;
    }

    private String toSorts (Sort sort) {
        String sortCols = null;
        if(null != sort){
            List<String> sortList = Lists.newArrayList();
            sort.forEach(t -> {
                if(t.isAscending()){
                    sortList.add("+" + StringUtil.toLowerCamel(t.getProperty()));
                }else{
                    sortList.add("-" + StringUtil.toLowerCamel(t.getProperty()));
                }
            });
            sortCols = Joiner.on(",").join(sortList);
        }
        return sortCols;
    }

}
